<template>
  <div class="w-full h-80">
    <div class="w-full h-full mb-5" ref="ljsylzs" />
    <div>
      <span>时间选择: </span>
      <el-check-tag
        class="mr-2"
        v-for="(label, t) in Types"
        :key="t"
        :checked="type_ === t"
        @click="type_ = t"
        >{{ label }}</el-check-tag
      >
    </div>
  </div>
</template>

<script lang="ts">
import {
  ref,
  onMounted,
  defineComponent,
  computed,
  watch,
  shallowRef,
} from "vue";
import { echarts, ECOption } from "/@/components/Echart";
import { fundLjsylzs, FundLjsylzsRes, Types } from "/@/api/fund";
import { parseTime } from "/@/utils/tools";
import { LineSeriesOption } from "echarts/charts";
import { ECharts } from "echarts/core";

export default defineComponent({
  props: {
    code: { type: String, required: true },
  },
  setup(props) {
    const myChart = shallowRef<ECharts | null>(null);
    const type_ = ref("m6");
    const data = ref<FundLjsylzsRes[]>([]);
    const getData = async () => {
      let {
        data: { Data },
      } = await fundLjsylzs(props.code, type_.value as keyof typeof Types);
      data.value = Data;
    };
    getData();
    const legend = computed(() => {
      return data.value.map((v) => {
        return v.name;
      });
    });
    const xAxis = computed(() => {
      if (data.value.length > 0) {
        return data.value[0].data.map((v) => {
          return parseTime(v[0]);
        });
      }
      return [];
    });
    const series = computed(() => {
      return data.value.map((v) => {
        return {
          name: v.name,
          type: "line",
          stack: "Total",
          data: v.data.map((dd) => dd[1]),
        };
      });
    });
    const option = computed((): ECOption => {
      return {
        title: {
          text: "累计收益率走势",
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: legend.value,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: xAxis.value,
        },
        yAxis: {
          type: "value",
        },
        series: series.value as LineSeriesOption,
      };
    });
    const ljsylzs = ref(null);

    onMounted(() => {
      myChart.value = echarts.init(ljsylzs.value as unknown as HTMLElement);
      window.onresize = () => {
        myChart.value?.resize();
      };
    });
    watch(data, (v) => {
      if (v) {
        myChart.value?.setOption(option.value);
        myChart.value?.resize();
      }
    });
    watch(type_, () => {
      getData();
    });

    return {
      ljsylzs,
      legend,
      xAxis,
      series,
      type_,
      data,
      getData,
      option,
      Types,
    };
  },
});
</script>